from django.contrib.auth.models import Permission, Group
from django.contrib.contenttypes.models import ContentType
from rest_framework.serializers import ModelSerializer

from apps.users.models import User


class PermissionSerializers(ModelSerializer):
    """权限管理"""
    class Meta:
        model= Permission
        fields = "__all__"

class Content_typeSerializer(ModelSerializer):
    """保存权限"""
    class Meta:
        model:ContentType
        fields = "__all__"


class GroupModelSerializer(ModelSerializer):
    """组管理"""
    class Meta:
        model = Group
        fields = "__all__"

class AdminModelSerializer(ModelSerializer):
    """管理员管理"""
    class Meta:
        model = User
        fields = "__all__"
        extra_kwargs = {
            'password':{
                'write_only':True
            }
        }

    def create(self, validated_data):
        """新增管理员"""
        user = super().create(validated_data)

        user.set_password(validated_data.get('password'))
        user.is_staff = True
        user.save()

        return user

    def update(self, instance, validated_data):
        """修改管理员"""
        # 调用父类实现数据更新
        super().update(instance, validated_data)
        # 获取密码,并进行判断是否用户修改了密码
        password = validated_data.get('password')
        if password is not None:
            instance.set_password(password)
            instance.save()

        return instance
